package com.qf.sportsevent.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.qf.sportsevent.R;
import com.qf.sportsevent.adapter.CommonRecyclerAdapter;
import com.qf.sportsevent.databinding.ActivityNewsDetailBinding;
import com.qf.sportsevent.entity.NewsContentsEntity;
import com.qf.sportsevent.entity.NewsDetailCommentEntity;
import com.qf.sportsevent.entity.NewsDetailCommentNumEntity;
import com.qf.sportsevent.entity.NewsDetailCommentsEntity;
import com.qf.sportsevent.entity.NewsDetailEntity;
import com.qf.sportsevent.entity.NewsDetailListEntity;
import com.qf.sportsevent.util.FastEventBus;
import com.qf.sportsevent.util.HttpUtils;
import com.qf.sportsevent.util.RecyclerItemLayoutManager;
import com.qf.sportsevent.util.UrlManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NewsDetailActivity extends AppCompatActivity{
    private ActivityNewsDetailBinding binding;
    private CommonRecyclerAdapter<Object> adapter;
    private int finishUrlCount;
    private NewsDetailEntity detailEntity;
    private List<NewsContentsEntity> listEntity;
    private NewsDetailCommentNumEntity commentNumEntity;
    private NewsDetailCommentEntity commentEntity;
    public final static int FINISH_DOWNLOAD = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_news_detail);
        adapter = new CommonRecyclerAdapter<>(this,new ArrayList(), RecyclerItemLayoutManager.getLayoutMap());
        binding.detailRecycler.setAdapter(adapter);
        binding.setActivity(this);

        Intent intent = getIntent();
        int id = intent.getIntExtra("id", -1);
        int commentId = intent.getIntExtra("dashboard_id",-1);
        int commentNum = intent.getIntExtra("dashboard_data",-1);

        if(id!=-1){
            String url = UrlManager.getCommonNewsUrl(id);
            if(url != null){
                HttpUtils.okHttpAsyncGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {}
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String jsonStr = response.body().string();
                        detailEntity = JSON.parseObject(jsonStr,NewsDetailEntity.class);
                        checkDownloadProgress();
                    }
                });
            }
            String listUrl = UrlManager.getListNewsUrl(id);
            if (listUrl != null) {
                HttpUtils.okHttpAsyncGet(listUrl, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {}
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String jsonStr = response.body().string();
                        listEntity = JSON.parseObject(jsonStr,NewsDetailListEntity.class).getData().getRecs();
                        checkDownloadProgress();
                    }
                });
            }
        }

        if(commentNum!=-1){
            String commentNumUrl = UrlManager.getCommentNumUrl(commentNum);
            if (commentNumUrl != null) {
                HttpUtils.okHttpAsyncGet(commentNumUrl, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {}
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String jsonStr = response.body().string();
                        commentNumEntity = JSON.parseObject(jsonStr,NewsDetailCommentNumEntity.class);
                        checkDownloadProgress();
                    }
                });
            }
        }

        if(commentId!=-1){
            String commentUrl = UrlManager.getCommentUrl(commentId);
            if (commentUrl != null) {
                HttpUtils.okHttpAsyncGet(commentUrl, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {}
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String jsonStr = response.body().string();
                        commentEntity = JSON.parseObject(jsonStr,NewsDetailCommentEntity.class);
                        checkDownloadProgress();
                    }
                });
            }
        }

    }

    public synchronized void checkDownloadProgress(){
        if(++finishUrlCount == 4){
            FastEventBus bus=new FastEventBus();
            bus.setCode(FINISH_DOWNLOAD);
            EventBus.getDefault().post(bus);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBusArrived(FastEventBus bus){
        if(bus.getCode() == FINISH_DOWNLOAD){
            if(detailEntity!=null) {
            NewsContentsEntity data = detailEntity.getData();
            if (data != null) {
                data.setDetail(true);
                adapter.add(data);
            }
            }
            if(listEntity!=null && listEntity.size()>0){
                adapter.add("推荐阅读");
                adapter.addAll(listEntity);
            }
            if(commentNumEntity != null && commentNumEntity.getData()>0){
                adapter.add(commentNumEntity.getData()+"条评论");
            }
            if (commentEntity != null && commentEntity.getData() != null) {
                List<NewsDetailCommentsEntity> comments = commentEntity.getData().getComments();
                if(comments != null && comments.size()>0){
                    adapter.addAll(comments);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
